﻿using M_Purchase.Api.Appliction.Command.PurchCommand;
using M_Purchase.Domain;
using M_Purchase.Domain.DTO;
using M_Purchase.Repository.PurchaseInterface;
using MediatR;

namespace M_Purchase.Api.Appliction.CommandHandlers.PurchCommandHandler
{
    /// <summary>
    /// 显示采购信息（入库出库）
    /// </summary>
    public class InListCommandHandler : IRequestHandler<InListCommand, PageDTO<Purch>>
    {
        private readonly IPurchRepository _purchRepository;
        public InListCommandHandler(IPurchRepository purchRepository)
        {
            _purchRepository = purchRepository;
        }
        public async Task<PageDTO<Purch>> Handle(InListCommand request, CancellationToken cancellationToken)
        {
            var PurList = await _purchRepository.GetAsync(d => !d.IsDeleted);
            if (!string.IsNullOrEmpty(request.PurchaseCode))
            {
                PurList = PurList.Where(d => d.PurchaseCode.Contains(request.PurchaseCode)).ToList();
            }
            if (!string.IsNullOrEmpty(request.CreatedDate))
            {
                PurList = PurList.Where(d => d.CreatedDate == Convert.ToDateTime(request.CreatedDate)).ToList();
            }
            if (!string.IsNullOrEmpty(request.InventoryState))
            {
                PurList = PurList.Where(d => d.InventoryState == request.InventoryState).ToList();
            }
            if (request.PageSize == null)
            {
                request.PageSize = PurList.Count();
            }
            if (request.PageIndex == null)
            {
                request.PageIndex = 1;
            }
            PageDTO<Purch> page = new PageDTO<Purch>();
            page.TotalCount = PurList.Count();
            page.PageCount = (int)Math.Ceiling(page.TotalCount * 1.0 / (int)request.PageSize);
            page.list = PurList.OrderByDescending(d => d.CreatedBy).Skip((int)(request.PageIndex - 1) * (int)request.PageSize).Take((int)request.PageSize).ToList();
            return page;
        }
    }
}
